import json


class Step(object):
    playbook = None
    arguments = {}
    right = None

    def __init__(self, *args, **kwargs):
        if not self.playbook:
            self.playbook = kwargs.get("playbook")
        if not self.arguments:
            self.arguments = kwargs.get("arguments")
        if not self.right:
            self.right = kwargs.get("right")

    def run(self):
        print("run", self.playbook)

    def serialize(self):
        return {
            "playbook": self.playbook,
            "arguments": self.arguments,
            "right": self.right
        }


class Engine(object):
    steps = []
    name = None

    def __init__(self, *args, **kwargs):
        self.name = kwargs.get("name")

    def add(self, step):
        self.steps.append(step)

    def pre(self, step):
        # True 有权限
        # False 无权限
        return True

    def post(self, step):
        pass

    def run(self):
        for step in self.steps:
            if self.pre(step):
                step.run()
            else:
                raise
            self.post(step)

    def serialize(self):
        data = {"name": self.name}
        data["steps"] = []
        for step in self.steps:
            data["steps"].append(step.serialize())
        return json.dumps(data)

    @classmethod
    def create(cls, _data):
        data = json.loads(_data)
        e = cls(name=data["name"])
        for step in data["steps"]:
            e.add(Step(playbook=step["playbook"], arguments=step["arguments"],
                right=step["right"]))
        return e

